<?php

namespace App\Http\Controllers\Auth;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Libs\Sms;
use App\Models\Message;
use App\Models\SmsCode;
use App\Models\Team;
use App\User;
use Carbon\Carbon;
use Hashids\Hashids;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Support\Facades\Input;

class IndexController extends Controller
{
    protected $auth;

    public function __construct(Guard $auth, Request $request)
    {
        $this->auth = $auth;
        if (preg_match('#^api/changchun/login#', $request->path())
        ) {
            parent::__construct();
            return;
        }
    }

    public function login()
    {
        $vars = [];
        return view('admin.index')->with('vars', json_encode($vars));
    }

    public function postLogin(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'password' => 'required',
        ]);
        $name = $request->get('name');
        $password = $request->get('password');
        $user = User::whereRaw('username=? AND type <> 1', [$name])->first();
        if ($user && $this->auth->attempt([
                'username' => $user->username,
                'type' => $user->type,
                'password' => $password
            ], false)
        ) {
//      Log::info($this->auth->user());
            return $this->returnJSON(null, 0, '登录成功', 200, [
                'UPDATE_UNREAD_COUNT' => Message::where('to_user_id', '=', $request->user()->id)->where('is_read', '=', 0)->count()
            ]);
        }
        // 第一次登录，自动创建用户。
        if (!$user) {
            $adminsCount = User::where('type', '=', 4)->count();
            if (!$adminsCount) {
                $user = new User();
                $user->fill([
                    'username' => $name,
                    'pwd' => bcrypt($password),
                    'type' => '4',
                    'org_id' => 0
                ]);
                $user->save();
                $this->auth->login($user);
                return $this->returnJSON(null, 0, '登录成功');
            }
        }
        return $this->returnJSON(null, 405, '登录失败，用户名或者密码错误');
    }

    // 长春登录
    public function changChunLogin(Request $request)
    {
        $this->validate($request, [
            'requestToken' => 'required',
        ]);
        $requestToken = $request->get('requestToken');
//        Log::info($requestToken);

#私钥
        $private_key = '-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgw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nSVon3 
A2DmEwb8ywKBgQCbTdcrwqhs8m7vcxTSt5g4TT1EsCLI/zpoJ7qPjLkaS4RfjoPF 
/9p7ZFu9piru+2WJ8+pBPbbfWt6HHMCgVlqWyLHs3IG3DGHLNgeyLnr20xjxJvGg 
kRGx3v6wNzWaAqAV0O3fmwFfOxQTNmjNivQd0aPNKh1iSZakL2XnLdXxkQKBgQCw 
xv1cPrYO7nuV8I/D6xT4d6reymN8nY1nxag7u9nFcrjG8wbbxeaSIPkt4Nszzo3i 
uV1vHhj5S1OzYeM6YPvz7dWM3MutPW6xbFJtCsOuY/mdDzrztb0zvmrLCTI5hnZn 
FDKy2ae6dIb8jegIP4ijPmdcf7G6IQYQk3oDThZiTwKBgAPupxMwlYM7zBRES0X3 
Uk36ekxisgKpWkEfoM3NrMdu/8DlUHoyR/UyiSMRCE777FaQP6JZZwI6y6sjoIn6 
WSd30oaTQOHlr+LuxFK2X4FyTtsgUTu3fs/193kUaJIUF+A2Tqvhw6wOaR1HS1jW 
w0z80yEA4uOipkowwGaUl2S/
-----END PRIVATE KEY-----';

        $pi_key = openssl_pkey_get_private($private_key);
        $requestToken = str_replace(' ', '+', $requestToken);
        openssl_private_decrypt(base64_decode($requestToken), $decrypted_data, $pi_key);
        Log::info('解密前：'.$requestToken);
        Log::info('解密后：'.$decrypted_data);
        $data = explode(',', $decrypted_data);
        try {
            if (count($data) === 4 && $data[2] && strlen($data[2]) > 14) {
                $id = substr($data[2], 6, strlen($data[2]) - 14);
                Log::info($id);
//                $user = User::where('id', $id)->where('type', '=', 2)->where('org_id', 33)->get();
                $user = User::find($id);
//                            dd($user);

                if ($user && $user->org_id == 33) {
                    $this->auth->login($user);
                    return redirect('/home');
                }

            }
        } catch (\Exception $e) {
            Log::error($e->getMessage());
        }
        return redirect('/login');

    }

    public function logout(Request $request)
    {
        $this->auth->logout();

        if ($request->has('back')) {
            return redirect($request->get('back'));
        }

        return view('admin.index')->with('vars', 'null');
    }

    public function postLogout()
    {
        $this->auth->logout();
        return $this->returnJSON(null);
    }

    public function postRegister(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'username' => 'required|unique:user',
            'password' => 'required|confirmed',
            'aggree' => 'required',
            'org_code' => 'required',
            'phone' => 'required',
            'code' => 'required',
        ]);

        $hasIds = new Hashids('', 10);
        $org_id = $hasIds->decode($request->input('org_code'));
        if (empty($org_id)) {
            throw new \Exception('非法操作');
        } else if (is_array($org_id)) {
            $org_id = $org_id[0];
        }
        $parentTeam = $request->input('parent_id') ? Team::find($request->input('parent_id')) : null;

        if ($parentTeam && $parentTeam->org_id != $org_id) {
            throw new \Exception('非法操作');
        }

        $count = Team::where('org_id', '=', $org_id)->where('name', '=', $request->input('name'))->count();

        if ($count) {
            return response()->json([
                'status' => 422,
                'msg' => '验证不通过',
                'errors' => [
                    'name' => '团队名称已经存在'
                ]
            ], 200);
        }

        $phone = $request->input('phone');
        $user = User::whereRaw('phone=? AND type <> 1', [$phone])->first();
        if ($user) {
            return response()->json([
                'status' => 422,
                'msg' => '验证不通过',
                'errors' => [
                    'phone' => '手机号已被注册'
                ]
            ], 200);
        }
        $verifyCode = $request->input('code');
        //检查验证码
        $checkSms = SmsCode::checkVerifyCode($phone, $verifyCode, 1);
        if (!$checkSms) {
            return $this->returnJSON(null, 10001, '短信验证码错误,请重新输入');
        }

        $team = new Team();
        $team->fill([
            'name' => $request->input('name'),
            'org_id' => $org_id,
            'parent_id' => $parentTeam ? $parentTeam->id : 0,
            'verify_status' => -1,
            'verify_msg' => '',
            'user_id' => 0,
            'type' => '',
            'service_target' => '',
            'slogan' => '',
            'logo' => '',
            'photo' => '',
            'identifier' => '',
            'contact_name' => '',
            'contact_phone' => '',
            'contact_email' => '',
            'province_id' => 0,
            'province_name' => '',
            'city_id' => 0,
            'city_name' => '',
            'county_id' => 0,
            'county_name' => '',
            'addr' => '',
            'legal_person' => '',
            'legal_person_id' => '',
            'legal_person_phone' => '',
            'certificate_photo' => '',
            'team_photo' => '',
            'abstract' => '',
            'reward_time' => 0,
            'auth_exempt_project' => 0,
            'join_type' => 2,
        ]);

        if ($team->save()) {
            $user = new User();
            $user->fill([
                'username' => $request->input('username'),
                'pwd' => bcrypt($request->input('password')),
                'phone' => $phone,
                'type' => 2,
                'team_id' => $team->id,
                'org_id' => $org_id
            ]);

            if ($user->save()) {
                $this->auth->login($user);
                $team->fill([
                    'user_id' => $user->id
                ]);
                if ($team->save()) {
                    $orgManager = User::with('org')->where('org_id', '=', $org_id)->first();

                    $msg = new Message();
                    $msg->fill([
                        'to_user_id' => $user->id,
                        'title' => '欢迎注册使用'.strval($orgManager->org->name),
                        'content' => '请您尽快完善团队信息',
                        'from_user_id' => $orgManager->id,
                        'publish_time' => (new Carbon())->toDateTimeString(),
                        'type' => '1'
                    ]);
                    $msg->save();

                    return $this->returnJSON(null, 0, '注册成功');
                }
            }
        }

        return $this->returnJSON(null, 500, '注册失败，请联系客服');
    }

    public function verifyphone(Request $request)
    {
        $rules = [
            'phone' => 'required|is_phone',
        ];

        $validator = Validator::make(Input::all(), $rules);


        if ($validator->fails()) {
            $errors = $validator->errors();
            return $this->returnJSON(null, 10001, implode(' ', $errors->all()));
        }

        $phone = $request->input('phone');

        if ($request->get('type', 0) == 1) {
            // 后台注册
            // 注册需要判断该手机号是否已经被注册，存在则验证不通过
            $user = User::whereRaw('phone=? AND type <> 1', [$phone])->first();
            if ($user) {
                return $this->returnJSON(null, 20001, '手机号已被注册!');
            }
        }


        if ($request->get('type', 0) == 2) {
            // 后台找回密码
            // 默认找回手机号，必须手机号已经存在；如果是注册，必须带上register=1
            $user = User::whereRaw('phone=? AND type <> 1', [$phone])->first();
            if (!$user) {
                return $this->returnJSON(null, 20001, '手机号不存在!');
            }
        }


        $ip = $request->getClientIp();

        $node = new SmsCode();
        $code = $node->getVerifyCode($phone, $ip, 1);

        if ($code === false) {
            return $this->returnJSON(null, 20001, '手机号异常,发送验证码失败!');
        }

        $sms = new Sms();
        $ret = $sms->sendTemplateSMS($phone, array($code, '10分钟'), 209261);

        if ($ret->statusCode !== '000000') {
            return $this->returnJSON(null, 30001, $ret->statusMsg);
        }
        return $this->returnJSON(null);
    }

    public function sms(Request $request)
    {
        $rules = [
            'phone' => 'required|is_phone',
            'code' => 'required',
        ];
        $validator = Validator::make(Input::all(), $rules);

        if ($validator->fails()) {
            $errors = $validator->errors();
            return $this->returnJSON(null, 10001, implode(' ', $errors->all()));
        }

        $phone = $request->input('phone');
        $verifyCode = $request->input('code');
        //检查验证码
        $checkSms = SmsCode::checkVerifyCode($phone, $verifyCode, 1);
        if (!$checkSms) {
            return $this->returnJSON(null, 10001, '短信验证码错误,请重新获取验证码!');
        }

        $user = User::whereRaw('phone=? AND type <> 1', [$phone])->first();
        if ($user) {
            Auth::login($user);
            $user->fill([
                'pwd' => bcrypt('88888888')
            ])->save();
//      Log::info($this->auth->user());
            return $this->returnJSON(null, 0, '登录成功, 密码已重置为 88888888，请前往用户中心中修改密码', 200, [
                'UPDATE_UNREAD_COUNT' => Message::where('to_user_id', '=', $request->user()->id)->where('is_read', '=', 0)->count()
            ]);
        } else {
            return $this->returnJSON(null, 500, '登录失败，程序错误');
        }
    }
}
